!function () {
    layui.config({base: '/layui/lay/modules/'}).use(['table', 'laydate', 'dateformat','upload', 'form','common'], function () {
        //定义
        var $ = layui.jquery,
            table = layui.table,
            form = layui.form,
            upload = layui.upload,
            dateformat = layui.dateformat,
            common = layui.common,//自定义模块
            laydate = layui.laydate;//自定义状态控件

        //富文本编辑器
        //var E = window.wangEditor;
        //定义总变量
        var Store = {
            tableId: "storeTable",    //表格id
            storeType:{'':'全部'},              //父菜单节点
            condition: {                //查询条件
                name: "",
                proId:"",
                cityId: ""
            },
            //editor :new E('#StoreText') //富文本内容
        }

        /***
         * 初始化省份城市
         */
        Store.initProvince = function(proId,cityId,proName,cityName){

            var $cityCode = $(cityId),$provinceCode = $(proId);
            //加载省份下拉框选项
            $provinceCode.empty().append('<option value="">请选择</option>');
            for (var i in cities) {
                if( i == proName ){
                    $provinceCode.append('<option value="'+i+'" selected>' + i + '</option>');
                    //构建城市select
                    var s = cities[proName];
                    $cityCode.html('<option value="">请选择</option>');
                    for (var c in s) {
                        if( c == cityName ){
                            $cityCode.append('<option value="'+c+'" selected>' + c + '</option>');
                        }else{
                            $cityCode.append('<option value="'+c+'">' + c + '</option>');
                        }
                    }
                }else{
                    $provinceCode.append('<option value="'+i+'">' + i + '</option>');
                }
            }
            layui.form.render('select');

            //根据省份下拉框值，加载相应的城市下拉框选项，并定位地图中心点
            form.on('select(selPro)',function (data) {
                var s = cities[data.value];
                $cityCode.html('<option value="">请选择</option>');
                for (var i in s) {
                    $cityCode.append('<option value="'+i+'">' + i + '</option>');
                }
                layui.form.render();
            });

        }

        /**
         * 初始化列表列
         * **/
        Store.initColumn = function(){
            return [[
                /*{type: 'checkbox', fixed: 'left'},*/
                {field: 'id', title: 'ID', width: 80,hide:true},
                {field: 'name', title: '门店名称', width: 160},
                {field: 'tel', title: '门店电话', width: 260},
                {field: 'proName', title: '省份', width: 100},
                {field: 'cityName', title: '城市', width: 100},
                {field: 'addr' ,title :'门店地址',width:260},
                {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 280, align: 'center'}
            ]];
        }


        /**
         * 查询方法
         * **/
        Store.search = function(){
            var queryData = {};
            queryData["name"] = $("#name").val();
            queryData["tel"] = $("#tel").val();
            queryData["proName"] = $("#proName").val();
            queryData["cityName"] = $("#cityName").val();
            table.reload(Store.tableId, {where: queryData,page: {curr: 1}});
        }

        /**
         * 新增记录
         * **/
        Store.addRecord =function (){

            //初始化表单
            $('#editForm')[0].reset();
            $('#editForm :input').val("");//重置所有的input
            $("#imgDiv").attr("src",'../../images/upload.png');//重置上传图片
            //初始化省份城市
            Store.initProvince('#editForm [name=proName]','#editForm [name=cityName]');
            layui.form.render();

            //打开弹出层
            layer.open({
                type: 1, maxmin: true, title: '添加门店信息', shade: 0.4, shadeClose: false,
                area: ['850px', '600px'], content: $('#editForm').show(), btn: ['保存', '取消'],
                yes: function () {
                    $('#saveRecord').click();
                }, btn2: function () {
                    layer.closeAll();
                }, end: function () {
                    $('#editForm').hide();
                }
            });
        }

        /**
         * 修改记录
         * **/
        Store.editRecord =function (data){
            //初始化数据
            $.ajax({
                async: false,
                url: '/store/findStore?id=' + data.id,
                success: function (result) {
                    if (result && result.code == 200) {
                        var data = result.data;
                        //初始化表单
                        //初始化省份城市
                        Store.initProvince('#editForm [name=proName]','#editForm [name=cityName]',data.proName,data.cityName);
                        form.render('radio').val('editForm', data);
                        $("#imgDiv").attr("src",data.url);
                        //打开弹出层
                        layer.open({
                            type: 1, maxmin: true, title: '修改门店信息', shade: 0.4, shadeClose: false,
                            area: ['700px', '600px'], content: $('#editForm').show(), btn: ['保存', '取消'],
                            yes: function () {
                                $('#saveRecord').click();
                            }, btn2: function () {
                                layer.closeAll();
                            }, end: function () {
                                $('#editForm').hide();
                            }
                        });
                    }else
                        layer.alert(result.msg || '请求失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        }

        /**
         * 删除记录
         * **/
        Store.deleteRecord =function (data){
            $.ajax({
                async: false,
                type: 'post',
                url: '/store/delete?id=' + data.id,
                success: function (result) {
                    if (result && result.code == 200) {
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        Store.search();
                    }
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        }

        //初始化渲染列表
        //日期
        laydate.render({
            elem: '#startDate'
        });
        laydate.render({
            elem: '#endDate'
        });

        //初始化省份城市
        Store.initProvince('#proName','#cityName');

        table.render({
            elem:"#storeTable"
            ,url:"/store/listPage"
            ,cellMinWidth:80
            ,request: {pageName: 'pageNum', limitName: 'pageSize'}
            ,page: true
            ,cols:Store.initColumn(),
            cellMinHeight:200

        });

        // 搜索按钮点击事件
        $('#btnSearch').click(function () {
            Store.search();
        });

        // 重置点击事件
        $('#resetSearch').click(function () {
            $('#queryTools input').val('');
            $('#queryTools select').val('');
            Store.search();
        });

        // 添加按钮点击事件
        $('#btnAdd').click(function () {
            Store.addRecord();
        });

        //监听工具条
        table.on('tool(' + Store.tableId + ')',function(obj){
            var data = obj.data;
            var layEvent = obj.event;
            if( layEvent ==='detail'){
                //查看
                return false;
            } else if( layEvent ==='del'){
                layer.confirm('确定要删除该门店信息吗？', function (index) {
                    Store.deleteRecord(data);
                    return false;
                });
            } else if( layEvent ==='edit'){
                Store.editRecord(data);
                return false;
            }
        });

        //自定义验证规则
        form.verify({
            nameLen: [
                /^[\d\D]{1,32}$/
                ,'门店名称最多输入32个字'
            ],
            tel:[
                /^[0-9]{4}[-][0-9]{1,11}$/
                ,'门店电话格式不正确'
            ],
            telLen:[
                /^[\d\D]{1,16}$/
                ,'门店电话最多输入16个字'
            ],
            addrLen:[
                /^[\d\D]{1,128}$/
                ,'门店地址最多输入128个字'
            ]
        });

        //监听提交事件
        form.on('submit(editRecord)',function(data){

            var postUrl = !data.field['id'] ? '/store/addStore' : '/store/editStore';
            $.ajax({
                async: false, type: 'post', traditional: true, data: data.field, url: postUrl,
                success: function (data) {
                    if (data && data.code == 200) {
                        layer.closeAll();
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        Store.search();
                    } else
                        layer.alert(data.msg || '操作失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.closeAll();
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
            return false;
        });

    });
}();